const Joi = require("joi");
// 小程序爪渥 appId，appSecret
const appId = "wx370029975646f56b";
const appSecret = "0b34fdc2a8aa28d112c531968ffb0f22";
module.exports = class AppletController extends colpu.Controller {
  /**
   * @api {get} /applet/session 获取小程序获得session
   * @apiDescription 获取小程序获得session
   * @apiGroup 小程序
   * @apiVersion 1.0.0
   *
   * @apiSuccess {Number} status 状态码
   * @apiSuccess {String} message 消息
   * @apiSuccess {Object} data 返回结果
   * @apiSuccessExample {json} Success-Response:
   * HTTP/1.1 200 OK
   *  {
   *    "data": {
   *       session_key: "Z90S7D4gq458L4uHL45DRQ==",
   *       openid: "otkOl62PF1PBP58XamCe1bu1FNsE",
   *       unionid: "o-7CF6h9UKEtMQO95Oi4q1MSWPDs",
   *    },
   *    "status": 0,
   *    "message": "ok"
   *  }
   */

  // 小程序获得session
  async getSession(ctx) {
    await ctx.validateAsync({
      query: {
        code: Joi.string().required(),
      },
      status: 10001,
    });
    const { code } = ctx.query;
    const res = await ctx.$http(
      "https://api.weixin.qq.com/sns/jscode2session",
      {
        params: {
          appid: appId,
          secret: appSecret,
          js_code: code,
          grant_type: "authorization_code",
        },
      }
    );
    // 这里拿到用户的session，openid，unionid后可做用户登录注册并返回服务器端端access_token
    // {
    //   session_key: "Z90S7D4gq458L4uHL45DRQ==",
    //   openid: "otkOl62PF1PBP58XamCe1bu1FNsE",
    //   unionid: "o-7CF6h9UKEtMQO95Oi4q1MSWPDs",
    // };
    console.log(res);
    ctx.respond(res);
  }

  /**
   * @api {get} /applet/session 小程序获取用户的电话号码
   * @apiDescription 小程序获取用户的电话号码
   * @apiGroup 小程序
   * @apiVersion 1.0.0
   *
   * @apiSuccess {Number} status 状态码
   * @apiSuccess {String} message 消息
   * @apiSuccess {Object} data 返回结果
   * @apiSuccessExample {json} Success-Response:
   * HTTP/1.1 200 OK
   *  {
   *    "data": {
   *    },
   *    "status": 0,
   *    "message": "ok"
   *  }
   */
  async getPhoneNumber(ctx) {
    await ctx.validateAsync({
      query: {
        code: Joi.string().required(),
      },
      status: 10001,
    });
    const access_token = await this._getAccessToken(ctx);
    const { code } = ctx.query;

    // 获取access_token的接口地址
    const url = `https://api.weixin.qq.com/wxa/business/getuserphonenumber?access_token=
      ${access_token}`;
    const res = await ctx.$http.post(url, { code });
    const {
      phone_info: { countryCode, phoneNumber },
    } = res;
    console.log(res);
    // 这里拿到用户的phoneNumber后可做用户登录注册并返回服务器端端access_token
    ctx.respond({ countryCode, phoneNumber });
  }

  // 小程序获取用户access_token
  async _getAccessToken(ctx) {
    try {
      const res = await ctx.$http("https://api.weixin.qq.com/cgi-bin/token", {
        params: {
          grant_type: "client_credential",
          appid: appId,
          secret: appSecret,
        },
      });
      const { access_token } = res;
      // 在这里对 access_token 进行相应的处理和使用
      return access_token;
    } catch (error) {
      // 处理错误情况
      console.error("Failed to get access token:", error);
      throw new Error("Failed to get access token");
    }
  }
};
